package com.lechuang.mybatis.utils;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.ISqlSegment;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lechuang.common.request.PageRequest;

import static com.baomidou.mybatisplus.core.enums.SqlKeyword.*;

/**
 * <p>
 *
 * </p>
 *
 * @author liaoningbo
 * @since 2023-07-19
 */
public class MybatisPlusUtil {
    /**
     * <p>
     *     设置排序
     * </p>
     * @author liaoningbo
     * @since 2023/7/19
     */
    public static <T, M> void setOrder(LambdaQueryWrapper<T> queryWrapper, PageRequest<M> pageRequest) {
        String orderBy = pageRequest.getOrderBy();
        Boolean isAsc = pageRequest.getIsAsc();
        if(StrUtil.isEmpty(orderBy) || isAsc == null){
            return;
        }
        try {
            ISqlSegment[] sqlSegments = {ORDER_BY, () -> StrUtil.toUnderlineCase(orderBy), isAsc ? ASC : DESC};
            queryWrapper.getExpression().add(sqlSegments);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("设置排序出错：" + e.getMessage());
        }
    }
}
